const Wechat = require('../util/Wechat'),
    logger = require('log4js').getLogger()

module.exports = (req, res) => {
    require('../util/service').handlePost(req, res, (reqObj, resolve) => {
        if (!reqObj.code) {
            resolve({
                result: -1,
                msg: '缺少code'
            })
            return
        }
        var wechat = Wechat({
            AppID: 'wx226c3c9557c44304',
            AppSecret: '8bff6155d050947d06bf7802e69f4acb'
        })
        wechat.snsOauth2AccessToken({
            code: reqObj.code
        }).then(result => {
            if (result.openid) {
                req.session.wechat = {
                    openid: result.openid
                }
                const mongoMng = require('../mng/mongoMng')
                if (!mongoMng.db) {
                    logger.error('[' + __filename + ':' + __line + '] 未连接mongo')
                    resolve({
                        result: 1
                    })
                    return;
                }
                mongoMng.db.collection('user').find({
                    wechat: result.openid
                }).toArray((err, result) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        resolve({
                            result: 1
                        })
                        return
                    }
                    if (result.length == 0) {
                        resolve({
                            result: 1
                        })
                        return
                    }
                    require('../util/loginResolve')(result[0], req, resolve)
                })
            } else {
				logger.error('[' + __filename + ':' + __line + ']', JSON.stringify(result))
                resolve({
                    result: -1,
                    msg: result.errmsg
                })
            }
        }, result => {
            logger.error('[' + __filename + ':' + __line + ']', result)
            resolve({
                result: -1,
                msg: result
            })
        })
    })
}
